const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const Character = sequelize.define('Character', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'user_id',
    references: {
      model: 'users',
      key: 'id'
    }
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false,
    validate: {
      len: [1, 100]
    }
  },
  stats: {
    type: DataTypes.JSONB,
    allowNull: false,
    defaultValue: {},
    validate: {
      isValidStats(value) {
        const requiredStats = ['str', 'dex', 'pow', 'con', 'app', 'siz', 'int', 'edu'];
        for (const stat of requiredStats) {
          if (!(stat in value) || typeof value[stat] !== 'number' || value[stat] < 0 || value[stat] > 100) {
            throw new Error(`属性 ${stat} 必须是0-100之间的数字`);
          }
        }
      }
    }
  },
  skills: {
    type: DataTypes.JSONB,
    allowNull: false,
    defaultValue: {}
  },
  inventory: {
    type: DataTypes.JSONB,
    allowNull: false,
    defaultValue: [],
    validate: {
      isArray(value) {
        if (!Array.isArray(value)) {
          throw new Error('背包必须是数组格式');
        }
      }
    }
  },
  san: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 99,
    validate: {
      min: 0,
      max: 99
    }
  },
  hp: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    validate: {
      min: 0
    }
  },
  mp: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    validate: {
      min: 0
    }
  },
  isActive: {
    type: DataTypes.BOOLEAN,
    defaultValue: true,
    field: 'is_active'
  }
}, {
  tableName: 'characters',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  hooks: {
    beforeCreate: (character) => {
      // 计算生命值
      const con = character.stats.con || 0;
      const siz = character.stats.siz || 0;
      character.hp = Math.floor((con + siz) / 2);
      
      // 计算魔法值
      character.mp = character.stats.pow || 0;
    },
    beforeUpdate: (character) => {
      if (character.changed('stats')) {
        // 重新计算生命值和魔法值
        const con = character.stats.con || 0;
        const siz = character.stats.siz || 0;
        character.hp = Math.floor((con + siz) / 2);
        character.mp = character.stats.pow || 0;
      }
    }
  }
});

// 关联关系
Character.associate = (models) => {
  // 角色卡属于一个用户
  Character.belongsTo(models.User, {
    foreignKey: 'userId',
    as: 'user'
  });
};

module.exports = Character;
